package mscloud.handler;

import com.elevenms.common.core.response.ApiResponse;
import com.elevenms.common.core.response.ApiUtils;
import mscloud.config.CaptchaStrategyContext;
import mscloud.config.properties.CaptchaProperties;
import mscloud.service.CaptchaGenerationStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

/**
 * @Datetime: 2025年07月23日17:42
 * @Author: Eleven52AC
 * @Description: 验证码获取处理器
 */
@Component
public class ValidateCodeObtainHandler implements HandlerFunction<ServerResponse> {

    @Autowired
    private CaptchaStrategyContext captchaStrategyContext;

    @Autowired
    private CaptchaProperties captchaProperties;

    @Override
    public Mono<ServerResponse> handle(ServerRequest request) {
        if (!Boolean.TRUE.equals(captchaProperties.getEnabled())) {
            return ServerResponse
                    .status(HttpStatus.OK)
                    .body(BodyInserters.fromValue(ApiUtils.success("验证码功能已关闭")));
        }

        String strategyKey = captchaProperties.getType();
        CaptchaGenerationStrategy strategy = captchaStrategyContext.getStrategy(strategyKey);
        if (strategy == null) {
            return Mono.error(new IllegalStateException("未找到对应的验证码策略：" + strategyKey));
        }

        try {
            ApiResponse apiResponse = strategy.generationCaptchaCode();
            return ServerResponse
                    .status(HttpStatus.OK)
                    .body(BodyInserters.fromValue(apiResponse));
        } catch (Exception e) {
            return Mono.error(new RuntimeException("验证码生成异常", e));
        }
    }


}
